package com.barneyx.mshinfoplatform.web.front.info;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.barneyx.mshinfoplatform.common.ExResult;
import com.barneyx.mshinfoplatform.entity.info.InfoCateEntity;
import com.barneyx.mshinfoplatform.service.info.IInfoCateEntityService;
import org.apache.ibatis.annotations.Delete;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/info/cate/")
public class InfoCateController {

    @Resource
    private IInfoCateEntityService cateService;

    @GetMapping("list")
    public ExResult<List<InfoCateEntity>> getList(@RequestParam(value = "sort", required = false) boolean sort) {
        List<InfoCateEntity> list = cateService.list(new LambdaQueryWrapper<InfoCateEntity>().orderByDesc(InfoCateEntity::getInfoCateSort));
        if (sort) {
            List<InfoCateEntity> parent_list = list.stream().filter((c) -> c.getInfoCateParentId().equals("0")).collect(Collectors.toList());
            list.forEach((cate) -> {
                parent_list.forEach(tc -> {
                    if (tc.getInfoCateId().equals(cate.getInfoCateParentId())) {
                        tc.getChildren().add(cate);
                    }
                });
            });

            return ExResult.ofSuccess(parent_list);
        }
        return ExResult.ofSuccess(list);
    }


    @GetMapping("detail")
    public ExResult<InfoCateEntity> getDetail(@RequestParam("id") String cateId) {
        InfoCateEntity cate = cateService.getById(cateId);
        return ExResult.ofAuto(cate != null, cate);
    }


    @PostMapping("add")
    public ExResult<InfoCateEntity> createCate(@RequestBody InfoCateEntity infoCate) {
        return ExResult.ofAuto(cateService.save(infoCate), infoCate);
    }

    @PutMapping("update")
    public ExResult<InfoCateEntity> updateCate(@RequestBody InfoCateEntity infoCate) {
        return ExResult.ofAuto(cateService.updateById(infoCate), infoCate);
    }

    @Delete("delete")
    public ExResult<Boolean> deleteInfoCateById(@RequestParam("id") String cateId) {
        return ExResult.ofAuto(cateService.removeById(cateId));
    }



}
